package com.enoram.training1;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;

public class Email {
	
	private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 587;
    private String user;
    private String pass;
    private String host;

    private Session session;
	public Email(String user, String pass, String host) {
		super();
		this.user = user;
		this.pass = pass;
		this.host = host;
		setup();
	}
	
	public Email(String user, String pass) {
		this(user,pass,SMTP_HOST_NAME);
		
	}

	protected void setup(){
		Properties props = System.getProperties();

        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.quitwait", "false");
        props.put("mail.smtp.starttls.enable","true"); 
    
        session = Session.getDefaultInstance(props);	
	}
	
	public void send(String to, String subject, String body){
		
		try{
	      	MimeMessage msg = new MimeMessage(session);
	        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
	        msg.setFrom(new InternetAddress(user));
	        msg.setSentDate(new Date());
	        msg.setSubject(subject);
	        msg.setText(body);
	        Transport transport = session.getTransport("smtp");
	        msg.saveChanges();

	        transport.connect(host, SMTP_HOST_PORT, user, pass);

	        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
	        transport.close();
		}
		catch(AuthenticationFailedException afe){
			afe.printStackTrace();}
		catch(SendFailedException sfe){
			sfe.printStackTrace();}
		catch(MessagingException me){
			me.printStackTrace();}
		
	}

}
